package com.elite.groovy.callback

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import com.elite.groovy.util.Util
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: apiChatProducts
 * @description: 乐购乐销推送订单接口
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class apiChatProducts implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiChatProducts.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        String outData = "";

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData = "{\"retCode\":\"-1\",\"retMsg\":\"API被非法IP调用-Request Not Allow!" + IpAddressUtil.getIpAddress(request) + "\",\"message\":\"非法IP调用\"}";
            log.warn(outData);
            return outData;
        }


        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST") {
            outData = "{\"retCode\":\"-1\",\"retMsg\":\"HTTP请求调用类型错误，接口调用失败：" + getMethod + "\",\"message\":\"调用类型错误\"}";
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取调用数据
        String Syncpram = "";
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        try {
            // 解析请求报文
            Object callObject = JSON.parse(Syncpram);

            if (callObject instanceof JSONObject) {
                dealProductDB(eliteBean, (JSONObject) callObject, 1, 0);
                outData = "{\"retCode\":\"1\",\"retMsg\":\"操作成功(1)\",\"message\":null}";
            } else if (callObject instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) callObject;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dealProductDB(eliteBean, jsonObject, 0, i)
                }
                outData = "{\"retCode\":\"1\",\"retMsg\":\"操作成功(Arr)\",\"message\":null}";

            } else {
                log.warn("调用参数异常:" + Syncpram);
                outData = "{\"retCode\":\"-1\",\"retMsg\":\"调用参数异常\",\"message\":\"调用参数必须是JSONObject或JSONArray\"}";
            }

            log.debug("返回请求结果:" + outData);

        } catch (Exception e) {
            log.error(Util.getERRO(e));
            outData = "{\"retCode\":\"-1\",\"retMsg\":\"调用参数异常" + e.getMessage() + "\",\"message\":\"调用处理异常\"}";
        }
        return outData;

    }

    // 推送产品卡片数据处理
    public static boolean dealProductDB(EliteBean eliteBean, JSONObject callJson, int update_Flag, int loop_Num) {
        boolean deal_flag = true;
        log.info("推送产品卡片数据处理信息：" + callJson.toString());
        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            String token = callJson.getString("token");
            String customer_id = callJson.getString("customer_id");
            String order_no = callJson.getString("order");
            String title = callJson.getString("title");
            String subtitle = callJson.getString("subtitle");
            String img = callJson.getString("img");
            String product_url = callJson.getString("product_url");
            log.debug("推送产品卡片数据处理参数-token：" + token + " customer_id:" + customer_id + " order_no:" + order_no + " title:" + title + " subtitle:" + subtitle + " img:" + img + " product_url:" + product_url);

            // 处理主数据
            if (!KHUtil.isNull(customer_id) && !KHUtil.isNull(order_no)) {
                String insertSQL = "";
                int num = 0;

                // 如果通过JSONObject方式一次只有一条 或 一次推送了多条且当前为第一条 都需要将客户原始数据无效
                if (update_Flag == 1 || (update_Flag == 0 && loop_Num == 0)) {
                    insertSQL = '''Update Chat_Product_In
                                           Set Status = -1
                                         Where Customer_Id = ?''';
                    num = jt.update(insertSQL, customer_id);
                    log.debug("客户原始卡片数据处理-Chat_Product_In(" + customer_id + ") 数量：" + num);
                }

                // 将数据写入表
                insertSQL = '''Insert Into Chat_Product_In
                                  (Id, Token, Customer_Id, Order_No, Title, Subtitle, Img, Product_Url, Createdtime, Status)
                                Values
                                  (Uuid(), ?, ?, ?, ?, ?, ?, ?, Now(), 1)''';
                num = jt.update(insertSQL, token, customer_id, order_no, title, subtitle, img, product_url);
                log.debug("推送产品卡片数据处理-Chat_Product_In(" + customer_id + ") 数量：" + num);

            }

        } catch (Exception e) {
            log.error("推送产品卡片数据处理-数据处理错误", e);
            deal_flag = false;
        }

        return deal_flag;

    }
}